package com.study.thirdpartyeventconsumer.controller.google;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.qcloud.cos.utils.StringUtils;
import org.testng.annotations.Test;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.File;
import java.util.Date;
import java.util.Properties;

public class Mail163Utils {
    // 发件人邮箱和授权码（不是邮箱密码）
    private static final String SENDER_EMAIL = "jsp1822193376@163.com";
    private static final String AUTH_CODE = "HAd2qnxTgp2PbjzH";

    // 163邮箱SMTP服务器配置
    private static final String SMTP_HOST = "smtp.qq.com";
    private static final String SMTP_PORT = "465";

    /**
     * 发送邮件
     *
     * @param content  邮件正文
     * @param subject  邮件主题
     * @param toEmails 收件人邮箱数组
     * @param files    附件文件数组
     */
    public static void sendMail(String content, String subject, String[] toEmails,
                                File[] files) throws MessagingException {
        // 参数校验
        if (toEmails == null || toEmails.length == 0) {
            throw new IllegalArgumentException("收件人不能为空");
        }

        // 配置邮件服务器属性
        Properties props = new Properties();
        props.setProperty("mail.smtp.host", SMTP_HOST);
        props.setProperty("mail.smtp.auth", "true");
        props.setProperty("mail.smtp.port", SMTP_PORT);
        props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.setProperty("mail.smtp.socketFactory.port", SMTP_PORT);

        // 创建会话
        Session session = Session.getInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(SENDER_EMAIL, AUTH_CODE);
            }
        });

        // 创建邮件
        MimeMessage message = new MimeMessage(session);

        try {
            // 设置发件人
            message.setFrom(new InternetAddress(SENDER_EMAIL));

            // 设置收件人
            InternetAddress[] addresses = new InternetAddress[toEmails.length];
            for (int i = 0; i < toEmails.length; i++) {
                addresses[i] = new InternetAddress(toEmails[i]);
            }
            message.setRecipients(Message.RecipientType.TO, addresses);

            // 设置主题
            message.setSubject(subject, "UTF-8");

            // 创建多部分内容
            MimeMultipart multipart = new MimeMultipart();

            // 添加文本内容
            MimeBodyPart textPart = new MimeBodyPart();
            textPart.setText(content, "UTF-8");
            multipart.addBodyPart(textPart);

            // 添加附件
            if (files != null && files.length > 0) {
                for (File file : files) {
                    if (file != null && file.exists()) {
                        MimeBodyPart attachmentPart = new MimeBodyPart();
                        // 使用 FileDataSource 来处理附件
                        DataSource source = new FileDataSource(file);
                        attachmentPart.setDataHandler(new DataHandler(source));
                        // 设置附件文件名
                        attachmentPart.setFileName(MimeUtility.encodeText(file.getName()));
                        multipart.addBodyPart(attachmentPart);
                    }
                }
            }

            // 设置邮件内容
            message.setContent(multipart);

            // 设置发送时间
            message.setSentDate(new Date());

            // 保存设置
            message.saveChanges();

            // 发送邮件
            Transport.send(message);

        } catch (Exception e) {
            throw new MessagingException("发送邮件失败", e);
        }
    }

    /**
     * 重载方法：发送无附件邮件
     */
    public static void sendMail(String content, String subject, String... toEmails)
            throws MessagingException {
        sendMail(content, subject, toEmails, null);
    }


    /**
     * 发送普通邮件
     */
    @Test
    public void send0(String[] args) throws MessagingException {
        sendMail("测试内容", "测试主题", "receiver1@example.com", "receiver2@example.com");
        System.out.println("邮件发送成功！");
    }

    /**
     * 发送带附件邮件
     */
    @Test
    public void send1(String[] args) throws MessagingException {
        File[] files = new File[]{
                new File("test1.txt"),
                new File("test3.pdf")
        };
        sendMail("测试内容", "测试主题",
                new String[]{"1822193376@qq.com", "jsp1822193376@outlook.com"},
                files);
        System.out.println("邮件发送成功！");

    }

    //删除邮件
    @Test
    public void delete() throws MessagingException {
        EmailReader reader = new EmailReader("jsp1822193376@163.com", "HAd2qnxTgp2PbjzH");
        reader.deletePermanentlyById(1581928578);
    }

    //拉取邮件
    @Test
    public void fetch() {
//        String username = "faker520@admarv.com";
//        String password = "8VNYX4KywK9JXTJv";
        String username = "jsp1822193376@163.com";
        String password = "HAd2qnxTgp2PbjzH";

        EmailReader reader = new EmailReader(username, password);
        reader.readEmails();
    }


    @Test
    public void testHttpRequest() {
        HttpRequest request = new HttpRequest("https://www.google.com");
        HttpResponse execute = request.execute();
        execute.close();
        System.out.println(execute.getStatus());
        System.out.println(execute.body());

    }

}
